
from sqlalchemy.orm import Session
from src.db import engine
from src.db.table import ScheduleTask
from src.enums.task import TaskStatusEnum


def create(task: ScheduleTask):
    with Session(engine) as db:
        db.add(task)
        db.commit()
        db.refresh(task)
        return task

def get(task_uuid: str):
    with Session(engine) as db:
        task = db.query(ScheduleTask).filter(ScheduleTask.task_uuid == task_uuid).first()
        if not task:
            return None
        return task

def query_by_task_uuid(task_uuid: str):
    with Session(engine) as db:
        task = db.query(ScheduleTask).filter(ScheduleTask.task_uuid == task_uuid).first()
        if not task:
            return None
        return task

def query_all_by_task_status(task_status: TaskStatusEnum):
    with Session(engine) as db:
        task_list = db.query(ScheduleTask).filter(ScheduleTask.task_status == task_status.value).all()
        return task_list

def update(task: ScheduleTask):
    with Session(engine) as db:
        task_db = db.query(ScheduleTask).filter(ScheduleTask.task_uuid == task.task_uuid).first()
        if not task_db:
            return None
        db.merge(task)
        db.commit()
        db.refresh(task_db)
        return task_db

def delete(task_uuid: str):
    with Session(engine) as db:
        task = db.query(ScheduleTask).filter(ScheduleTask.task_uuid == task_uuid).first()
        if task:
            db.delete(task)
            db.commit()